<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2025/3/14} {16:12} 
 */

namespace wanghua\general_utility_tools_php\alipay;


use wanghua\general_utility_tools_php\tool\Tools;

class AlipayAuthSDK extends BaseAlipay
{

    /**
     * desc：获取支付宝用户授权信息
     * author：wh
     * @param $auth_code
     * @return mixed
     */
    public function getAuthInfo($auth_code){
        if(session('session_alipay_system_oauth_token_response')){
            //到期时间(s)
            $expires_in = session('session_alipay_system_oauth_token_response.expires_in');
            $auth_start = session('session_alipay_system_oauth_token_response.auth_start');
            //这里减去600秒防止刷新token的时候，时间还没到就过期了
            if(strtotime($auth_start)+$expires_in-600<time()){
                //过期了，刷新token
                $grantType = 'refresh_token';
                $alipay_system_oauth_token_response = $this->authExchangeOpenid($auth_code,$grantType);
                return $alipay_system_oauth_token_response;
            }else{
                return session('session_alipay_system_oauth_token_response');
            }
        }else{
            //实时获取
            $alipay_system_oauth_token_response = $this->authExchangeOpenid($auth_code);
            return $alipay_system_oauth_token_response;
        }
    }
    // 第一步：构建授权URL (引导用户跳转)
    function buildAuthUrl($auth_url)
    {
        //Tools::log_to_write_txt(['构建授权URL (引导用户跳转),$url'=>$auth_url]);
        $redirect_uri = urlencode($auth_url); // 回调地址需在支付宝后台配置
        $auth_url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?" .
            "app_id={$this->alipayConfig['app_id']}&" .
            "scope=auth_user&" .
            "redirect_uri={$redirect_uri}&" .
            "state=meebo";//自定义防CSRF参数
        //Tools::log_to_write_txt(['构建授权URL (引导用户跳转),$auth_url:'=>$auth_url]);
        return $auth_url;
    }

    // 第二步：获取授权码
    function authExchangeOpenid($auth_code,$grantType='authorization_code'){
        $root_path = Tools::get_root_path();
        require_once($root_path.'library/alipay-sdk-php-all/aop/AopCertClient.php'); // 支付宝官方SDK, 需从开放平台下载
        //AlipaySystemOauthTokenRequest
        require_once($root_path.'library/alipay-sdk-php-all/aop/request/AlipaySystemOauthTokenRequest.php');

        /** 初始化 **/
        $aop = new \AopCertClient;

        /** 支付宝网关 **/
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";

        /** 应用id,如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        $aop->appId = $this->alipayConfig['app_id'];

        /** 密钥格式为pkcs1，如何获取私钥请参考：https://opensupport.alipay.com/support/helpcenter/207/201602469554  **/
        $aop->rsaPrivateKey = $this->alipayConfig['alipay_app_private_key'];

        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        $appCertPath = $root_path.$this->alipayConfig['appCertPublicKey'];

        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        $alipayCertPath = $root_path.$this->alipayConfig['cert_path_alipayCertPublicKey_RSA2'];

        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        $rootCertPath = $root_path.$this->alipayConfig['cert_path_alipayRootCert'];

        /** 设置签名类型 **/
        $aop->signType= "RSA2";

        /** 设置请求格式，固定值json **/
        $aop->format = "json";

        /** 设置编码格式 **/
        $aop->charset= "utf-8";

        /** 调用getPublicKey从支付宝公钥证书中提取公钥 **/
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);

        /** 是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内 **/
        $aop->isCheckAlipayPublicCert = true;

        /** 调用getCertSN获取证书序列号 **/
        $aop->appCertSN = $aop->getCertSN($appCertPath);

        /** 调用getRootCertSN获取支付宝根证书序列号 **/
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);

        /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称alipay.system.oauth.token(换取授权访问令牌) **/
        $request = new \AlipaySystemOauthTokenRequest ();

        /** 值为authorization_code时，代表用code换取；值为refresh_token时，代表用refresh_token换取 **/
        $request->setGrantType($grantType);

        /** 授权码，用户对应用授权后得到，可参考文档：https://opendocs.alipay.com/open/284/web **/
        $request->setCode($auth_code);//"4b203fe6c11548bcabd8da5bb087a83b"

        /** 刷新令牌，上次换取访问令牌时得到。见出参的refresh_token字段 **/
        //$request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");


        $result = $aop->execute ($request);

        /**第三方调用（服务商模式），传值app_auth_token后，会收款至授权token对应商家账号，如何获传值app_auth_token请参考文档：https://opensupport.alipay.com/support/helpcenter/79/201602494631 **/
        //$result = $aop->execute ($request,null,$app_auth_token);

        $json = json_encode($result,JSON_UNESCAPED_UNICODE);
        //dump($json);;
        //array(3) {
        //  ["alipay_system_oauth_token_response"] => array(6) {
        //    ["access_token"] => string(40) "authusrB61082f01b2064753b039210cec7ddB44"
        //    ["auth_start"] => string(19) "2025-03-14 14:59:02"
        //    ["expires_in"] => int(1296000)
        //    ["re_expires_in"] => int(2592000)
        //    ["refresh_token"] => string(40) "authusrB85949807a38d4bffbd5c86ae7e797B44"
        //    ["open_id"] => string(47) "0442qO88pZKcduCIdYq7Z4N8y29dGoocWheNow1jt_QW1k4"
        //  }
        //  ["alipay_cert_sn"] => string(32) "9cbb86296783f52af85119eb59308f9a"
        //  ["sign"] => string(344) "qTFAlIaq3DO3L+9cjoXVJVhSipib8v2ot0Vb1cFEDdtVUH99eZsd33vDBDaKobf00XhVUBqx9WbL67GfEbUF94s6cPfGn9kHuYSMDKh5VRCUFF9TI+melq6GAXih9FbsgqUTY/OuAxz5GDfYL974CppSi7+uBodl0KCmt9kC6VgoC0tUe0s8MDC7LRWBEXheAwrfzMn8NzCpbJRSWRfmewRnBzNXC3SVV6KrMlQPaNcj4Wjl9JQxxCOFXRGqeCMF7pDLYPrChFy7TOCVE/ONUbBQcR1p3qqek3MO/QhpeumTB33VsfKTMQOKjWhEEfSYJa7vGxkQBnZ5QVVngzGVHg=="
        //}
        $json_arr = json_decode($json,true);
        $alipay_system_oauth_token_response = $json_arr['alipay_system_oauth_token_response'];
        session('session_alipay_system_oauth_token_response',$alipay_system_oauth_token_response);
        //$open_id = $alipay_system_oauth_token_response['open_id'];
        return $alipay_system_oauth_token_response;
    }

}